﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DP.Web.UI;
using CRM.BLL;
using CRM.Entity;
using DP.Data.OleDb;
using System.Data;
using System.Text;
using DP.Common;

namespace CRM.Web.MessagingManage
{
    public partial class SMSBatchSend : Common.PageBase
    {
        private T_SMS_SEND_BLL bll = new T_SMS_SEND_BLL();

        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnOK_Click(object sender, EventArgs e)
        {

            try
            {
                DataTable dt;
                //string connectionString = String.Format(configBll.GetCacheValueByName(this.Page, "OleDbConnStringExcel"), lblFullName.Text.Trim());            
                //dt = OleDbExcel.ExcelToDataTable(connectionString, ddlSheetName.SelectedValue);
                dt = NPOIExcelHelper.ExcelToDataTable(lblFullName.Text.Trim(), ddlSheetName.SelectedValue);



                T_SMS_SEND_Entity sendEntity = new T_SMS_SEND_Entity();
                sendEntity.BODYS = txtBODYS.Text;
                sendEntity.BUSINESSDIVISIONCODE = _userLoginInfo.UserEntity.BUSINESSDIVISIONCODE;
                sendEntity.BUSINESSDIVISIONID = _userLoginInfo.UserEntity.BUSINESSDIVISIONID;
                sendEntity.BUSINESSDIVISIONNAME = _userLoginInfo.UserEntity.BUSINESSDIVISIONNAME;
                sendEntity.CREATETIME = DateTime.Now;
                sendEntity.SDATE = DateTime.Now.ToString("yyyyMMdd");
                sendEntity.STIME = DateTime.Now.ToString("HHmmss");
                sendEntity.GHID = _userLoginInfo.UserEntity.USERID.ToString();
                sendEntity.UINFO = _userLoginInfo.UserEntity.USERNAME.ToString();
                sendEntity.LEVELS = 1;

                string fieldName = "电话号码";


                DataView dv = new DataView(dt);
                DataTable dvt = dv.ToTable(true, fieldName);

                StringBuilder sbTel = new StringBuilder();
                string tel = string.Empty;
                for (int i = 0; i < dvt.Rows.Count; i++)
                {
                    tel = dvt.Rows[i][fieldName].ToString();
                    if (tel.Length == 11)
                    {
                        sbTel.Append(tel).Append(";");
                    }
                    if ((i + 1) % 100 == 0 || (i + 1) == dvt.Rows.Count)
                    {
                        sendEntity.TEL_TO = sbTel.ToString().TrimEnd(new char[] { ';' });
                        bll.Insert(sendEntity);
                        sbTel = new StringBuilder();
                    }
                }
                PageHelper.ShowMessage("批量发送提交成功！");
            }
            catch (Exception ex)
            {
                PageHelper.ShowMessage("批量发送提交失败！" + ex.Message);
            }


        }

        /// <summary>
        /// Handles the Click event of the btnUpload control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void btnUpload_Click(object sender, EventArgs e)
        {
            String fileExtension = System.IO.Path.GetExtension(ImportFile.FileName).ToLower();
            if (!fileExtension.Equals(".xls"))
            {
                PageHelper.ShowMessage(this.Page, "文件上传类型错误！");
                return;
            }

            string filepath = UploadFile(this.Page, ImportFile);
            string filename = GetFileName(filepath);
            if (string.IsNullOrEmpty(filepath))
            {
                PageHelper.ShowMessage(this.Page, "文件上传失败！");
                return;
            }

            btnOK.Enabled = true;
            lblFullName.Text = filepath;
            lblFileName.Text = GetFileName(ImportFile.PostedFile.FileName);
            ddlSheetNameInit(filepath);
        }

        /// <summary>
        /// 显示Excel文件中的工作表
        /// </summary>
        /// <param name="fileName">Excel文件名</param>
        private void ddlSheetNameInit(string fileName)
        {
            ddlSheetName.DataSource = NPOIExcelHelper.GetSheets(fileName);
            ddlSheetName.DataTextField = "value";
            ddlSheetName.DataValueField = "value";
            ddlSheetName.DataBind();


            //DataView dv = null;
            //OleDbHelper oledbHelper = new OleDbHelper(String.Format(configBll.GetCacheValueByName(this.Page, "OleDbConnStringExcel"), fileName));
            //try
            //{
            //    string filename = ImportFile.PostedFile.FileName;
            //    if (filename == "")
            //    {
            //        PageHelper.ShowMessage(this.Page, "请选择需要导入的文件！");
            //        return;
            //    }
            //    DataTable dt = oledbHelper.GetSchemaTable();

            //    dv = new DataView(dt, " TABLE_NAME like '%$' ", "", DataViewRowState.CurrentRows);

            //    ddlSheetName.DataSource = dv;
            //    ddlSheetName.DataTextField = "TABLE_NAME";
            //    ddlSheetName.DataValueField = "TABLE_NAME";
            //    ddlSheetName.DataBind();
            //}
            //catch
            //{
            //    ddlSheetName.DataSource = dv;
            //    ddlSheetName.DataTextField = "TABLE_NAME";
            //    ddlSheetName.DataValueField = "TABLE_NAME";
            //    ddlSheetName.DataBind();
            //    PageHelper.ShowMessage(this.Page, "请检查导入的文件类型！");
            //    return;
            //}
        }


        /// <summary>
        /// 文件 上传方法
        /// </summary>
        /// <param name="page">当前页面</param>
        /// <param name="auc">上传控件</param>
        /// <returns>上传后的文件的服务器路径</returns>
        private string UploadFile(Page page, System.Web.UI.WebControls.FileUpload auc)
        {
            string temp = DateTime.Now.ToString("yyyyMMddHHmmss");
            string filename = auc.PostedFile.FileName;
            filename = GetFileName(filename);

            string filepath = HttpContext.Current.Request.MapPath(StaticConstant.UploadFilePath);

            int index = filename.LastIndexOf('.');
            if (index != -1)
            {
                filename = filename.Insert(index, temp);
            }
            else
            {
                filename += temp;
            }

            string fullpath = string.Empty;
            if (filepath.LastIndexOf("\\") == filepath.Length - 1)
            {
                fullpath = filepath + filename;
            }
            else
            {
                fullpath = filepath + "\\" + filename;
            }

            try
            {
                auc.PostedFile.SaveAs(fullpath);
            }
            catch
            {
                fullpath = null;
            }
            return fullpath;
        }

        /// <summary>
        /// 在绝对路径中，获取Excel文件名
        /// </summary>
        /// <param name="input">需要导入的Excel绝对路径</param>
        /// <returns></returns>
        private string GetFileName(string input)
        {
            return input.Substring(input.LastIndexOf("\\") + 1);
        }
    }
}
